/*
 * DestinationScreen.java
 *
 */
package com.gpsnav.screen;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.component.AutoTextEditField;
import javax.microedition.location.Coordinates;
import net.rim.device.api.ui.text.NumericTextFilter;
import net.rim.device.api.util.*;
import com.gpsnav.bo.*;
import com.gpsnav.dao.*;
import com.gpsnav.util.*;
import com.gpsnav.ui.*;
import com.gpsnav.file.*;
import java.util.Date;
import java.util.Calendar;
import net.rim.device.api.i18n.DateFormat;
import javax.microedition.location.*;

public class MarkWaypointScreen extends MainScreen {

    RichTextField richTextField = new RichTextField("");
    AutoTextEditField nameField = new AutoTextEditField("","");
    DateField dateField = new DateField("",0,DateFormat.DATETIME_DEFAULT);
    
//    AutoTextEditField descriptionField = new AutoTextEditField("","");
    CustomEditField descriptionField = new CustomEditField("", "");
    AutoTextEditField shortDescField = new AutoTextEditField("Short Description:   ","");
    AutoTextEditField longDescField = new AutoTextEditField("Long Description:   ","");
    
    AutoTextEditField latitudeField = new AutoTextEditField("","",10,BasicEditField.FILTER_REAL_NUMERIC);
    AutoTextEditField longitudeField = new AutoTextEditField("", "", 11, BasicEditField.FILTER_REAL_NUMERIC);

    AutoTextEditField latitudeDecField = new AutoTextEditField("","",7,BasicEditField.FILTER_REAL_NUMERIC);
    AutoTextEditField longitudeDecField = new AutoTextEditField("", "", 7, BasicEditField.FILTER_REAL_NUMERIC);

    AutoTextEditField latitudeIntMMField = new AutoTextEditField("","",2,BasicEditField.FILTER_INTEGER);
    AutoTextEditField longitudeIntMMField = new AutoTextEditField("", "", 2, BasicEditField.FILTER_INTEGER);

    AutoTextEditField latitudeIntField = new AutoTextEditField("","",2,BasicEditField.FILTER_INTEGER);
    AutoTextEditField longitudeIntField = new AutoTextEditField("", "", 3, BasicEditField.FILTER_INTEGER);

    String[] latDir = {"N","S"};
    String[] lonDir = {"E","W"};
//    ObjectChoiceField latitudeDirectionField = new ObjectChoiceField("", latDir,0);
//    ObjectChoiceField longitudeDirectionField = new ObjectChoiceField("", lonDir,0);
    ResizableChoiceField latitudeDirectionField = new ResizableChoiceField("", latDir,0, FIELD_LEFT);
    ResizableChoiceField longitudeDirectionField = new ResizableChoiceField("", lonDir,0, FIELD_LEFT);

    LabelField MGRSGridZoneNumLbl = new LabelField("Grid Zone Num: ");
    LabelField MGRSGridZoneAlphaLbl = new LabelField("Grid Zone Alpha: ");
    LabelField MGRSGridLbl = new LabelField("Grid: ");
    LabelField MGRSNorthingLbl = new LabelField("Northing: ");
    LabelField MGRSEastingLbl = new LabelField("Easting: ");

    NumericChoiceField MGRSGridZoneNumField = new NumericChoiceField("",1,60,1);
    String[] gridAlphaChoices = {"C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X"};
    ResizableChoiceField MGRSGridZoneAlphaField = new ResizableChoiceField("", gridAlphaChoices,0, FIELD_LEFT);

    AutoTextEditField MGRSGridField = new AutoTextEditField("", "", 11, BasicEditField.FILTER_UPPERCASE);

    AutoTextEditField MGRSNorthingField = new AutoTextEditField("", "", 11, BasicEditField.FILTER_REAL_NUMERIC);
    AutoTextEditField MGRSEastingField = new AutoTextEditField("", "", 11, BasicEditField.FILTER_REAL_NUMERIC);

   // Coordinates destination = null;
    Waypoint currentWaypoint = null;
    Options options = new Options();
    OptionsDAO oDao = new OptionsDAO();

    public MarkWaypointScreen() {
        options = oDao.loadOptions();
        Font fnt = richTextField.getFont().derive(Font.PLAIN, 1);
        Font fntBold = richTextField.getFont().derive(Font.BOLD, 1);
        try {
            FontFamily ff = FontFamily.forName(Options.getFontFamily());
            fnt = ff.getFont(FontFamily.TRUE_TYPE_FONT, Options.getEditFontSize()).derive(Font.PLAIN);
            fntBold = ff.getFont(FontFamily.TRUE_TYPE_FONT, Options.getEditFontSize()).derive(Font.BOLD);
        } catch(Exception e) {
        }

         LayoutGrid gw = new LayoutGrid(2);
         LabelField nameLbl = new LabelField("Wpt Name: ");
         nameLbl.setFont(fntBold);
         gw.add(nameLbl);
         nameField.setFont(fnt);
         gw.add(nameField);
         FlowFieldManager f1 = new FlowFieldManager();
         LabelField dateLbl = new LabelField("Date: ");
         dateLbl.setFont(fntBold);
         f1.add(dateLbl);
         dateField.setFont(fnt);
         f1.add(dateField);
         add(gw);
         add(f1);
         
         add(new CustomSeparatorField());
         
         LayoutGrid g = new LayoutGrid(2);

         switch (Options.getCoordFormat()) {
            case 0: //HorizontalFieldManager h = new HorizontalFieldManager();
                    //LayoutGrid g0 = new LayoutGrid(2);
                    LabelField latLbl = new LabelField("Latitude(-dd.ddddd)");
                    latLbl.setFont(fntBold);
                    latitudeField.setFont(fnt);
                    g.add(latLbl);
                    g.add(latitudeField);

                    //add(new SeparatorField());
                    //h = new HorizontalFieldManager();
                    LabelField lonLbl = new LabelField("Longitude(-ddd.ddddd)");
                    lonLbl.setFont(fntBold);
                    longitudeField.setFont(fnt);
                    g.add(lonLbl);
                    g.add(longitudeField);
                    //add(g);
                    //add(new SeparatorField());
                    break;

            case 1: //LayoutGrid g1 = new LayoutGrid(2);
                    LabelField lat1Lbl = new LabelField("Latitude");
                    lat1Lbl.setFont(fntBold);
                    g.add(lat1Lbl);
                    g.add(new LabelField(""));
                    
                    LabelField nsLbl = new LabelField("  N/S: ");
                    LabelField ddLbl = new LabelField("  dd: ");
                    LabelField mmLbl = new LabelField("  mm.mmmm: ");

                    nsLbl.setFont(fntBold);
                    ddLbl.setFont(fntBold);
                    mmLbl.setFont(fntBold);
                    latitudeDirectionField.setFont(fnt);
                    latitudeIntField.setFont(fnt);
                    latitudeDecField.setFont(fnt);
                    g.add(nsLbl);
                    g.add(latitudeDirectionField);
                    g.add(ddLbl);
                    g.add(latitudeIntField);
                    g.add(mmLbl);
                    g.add(latitudeDecField);

                    //add(new SeparatorField());
                    g.add(new LabelField(""));
                    g.add(new LabelField(""));

                    LabelField lon1Lbl = new LabelField("Longitude");
                    lon1Lbl.setFont(fntBold);
                    g.add(lon1Lbl);
                    g.add(new LabelField(""));

                    LabelField ewLbl = new LabelField("  E/W: ");
                    LabelField dddLbl = new LabelField("  ddd: ");
                    LabelField mm2Lbl = new LabelField("  mm.mmmm: ");

                    ewLbl.setFont(fntBold);
                    dddLbl.setFont(fntBold);
                    mm2Lbl.setFont(fntBold);
                    longitudeDirectionField.setFont(fnt);
                    longitudeIntField.setFont(fnt);
                    longitudeDecField.setFont(fnt);
                    g.add(ewLbl);
                    g.add(longitudeDirectionField);
                    g.add(dddLbl);
                    g.add(longitudeIntField);
                    g.add(mm2Lbl);
                    g.add(longitudeDecField);
                    //add(g1);
                    break;
            case 2: //LayoutGrid g1 = new LayoutGrid(2);
                    LabelField dms_lat1Lbl = new LabelField("Latitude");
                    dms_lat1Lbl.setFont(fntBold);
                    g.add(dms_lat1Lbl);
                    g.add(new LabelField(""));
                    
                    LabelField dms_nsLbl = new LabelField("  N/S: ");
                    LabelField dms_ddLbl = new LabelField("  dd: ");
                    LabelField dms_mmLbl = new LabelField("  mm: ");
                    LabelField dms_ssLbl = new LabelField("  ss.s: ");

                    dms_nsLbl.setFont(fntBold);
                    dms_ddLbl.setFont(fntBold);
                    dms_mmLbl.setFont(fntBold);
                    dms_ssLbl.setFont(fntBold);
                    latitudeDirectionField.setFont(fnt);
                    latitudeIntField.setFont(fnt);
                    latitudeDecField.setFont(fnt);
                    latitudeIntMMField.setFont(fnt);
                    g.add(dms_nsLbl);
                    g.add(latitudeDirectionField);
                    g.add(dms_ddLbl);
                    g.add(latitudeIntField);
                    g.add(dms_mmLbl);
                    g.add(latitudeIntMMField);
                    g.add(dms_ssLbl);
                    g.add(latitudeDecField);

                    //add(new SeparatorField());
                    g.add(new LabelField(""));
                    g.add(new LabelField(""));

                    LabelField dms_lon1Lbl = new LabelField("Longitude");
                    dms_lon1Lbl.setFont(fntBold);
                    g.add(dms_lon1Lbl);
                    g.add(new LabelField(""));

                    LabelField dms_ewLbl = new LabelField("  E/W: ");
                    LabelField dms_dddLbl = new LabelField("  ddd: ");
                    LabelField dms_mm2Lbl = new LabelField("  mm: ");
                    LabelField dms_ss2Lbl = new LabelField("  ss.s: ");

                    dms_ewLbl.setFont(fntBold);
                    dms_dddLbl.setFont(fntBold);
                    dms_mm2Lbl.setFont(fntBold);
                    longitudeDirectionField.setFont(fnt);
                    longitudeIntField.setFont(fnt);
                    longitudeDecField.setFont(fnt);
                    longitudeIntMMField.setFont(fnt);
                    g.add(dms_ewLbl);
                    g.add(longitudeDirectionField);
                    g.add(dms_dddLbl);
                    g.add(longitudeIntField);
                    g.add(dms_mm2Lbl);
                    g.add(longitudeIntMMField);
                    g.add(dms_ss2Lbl);
                    g.add(longitudeDecField);
                    //add(g1);
                    break;
            case 3: //HorizontalFieldManager h2 = new HorizontalFieldManager();
                    add(new LabelField("MGRS: "));
                    //LayoutGrid g3 = new LayoutGrid(2);
                    g.add(MGRSGridZoneNumLbl);
                    g.add(MGRSGridZoneNumField);
                    g.add(MGRSGridZoneAlphaLbl);
                    g.add(MGRSGridZoneAlphaField);
                    g.add(MGRSGridLbl);
                    g.add(MGRSGridField);
                    g.add(MGRSEastingLbl);
                    g.add(MGRSEastingField);
                    g.add(MGRSNorthingLbl);
                    g.add(MGRSNorthingField);
                    //add(g3);
                    break;
         }
         
         add(g);

        add(new CustomSeparatorField());
        
        LayoutGrid g2 = new LayoutGrid(1);
        CustomLabelField descLbl = new CustomLabelField("Description: ");
        descLbl.setFont(fntBold);
        descriptionField.setFont(fnt);
        g2.add(descLbl);
        g2.add(descriptionField);
        add(g2);
    }

    public void setWaypoint(Coordinates loc) {

        Coordinates c = loc;
        //destination = dest;
        if (c == null) {
            c = new Coordinates(0,0,0);
        }

        Waypoint wp = new Waypoint("WPT-"+WaypointsDAO.getNextId(), c.getLatitude(), c.getLongitude(), c.getAltitude());
        Date now = Calendar.getInstance().getTime();
        wp.setWptDate(now.getTime());
        //wp = new Waypoint("WPT-"+WaypointsDAO.getNextId(), 89,76,45);
        setWaypoint(wp);
    }

    public void setWaypoint(Waypoint wp) {
        currentWaypoint = wp;
        setFields(wp);
    }

    public void setFields(Waypoint wp) {

        //destination = dest;
        if (wp != null) {
            nameField.setText(wp.getName());
          switch (Options.getCoordFormat()) {

              case 0: latitudeField.setText(Double.toString(wp.getLatitude()));
                      longitudeField.setText(Double.toString(wp.getLongitude()));
                      break;

              case 1: String lat = Coordinates.convert(Math.abs(wp.getLatitude()),Coordinates.DD_MM);
                      String lon = Coordinates.convert(Math.abs(wp.getLongitude()),Coordinates.DD_MM);

                      latitudeDirectionField.setSelectedIndex((wp.getLatitude() > 0) ?0 : 1);
                      longitudeDirectionField.setSelectedIndex((wp.getLongitude() > 0) ?0 : 1);

                      latitudeIntField.setText(lat.substring(0,lat.indexOf(":")));
                      latitudeDecField.setText(lat.substring(lat.indexOf(":")+1,lat.length()));

                      longitudeIntField.setText(lon.substring(0,lon.indexOf(":")));
                      longitudeDecField.setText(lon.substring(lon.indexOf(":")+1,lon.length()));
                      break;

              case 2: String dms_lat = Coordinates.convert(Math.abs(wp.getLatitude()),Coordinates.DD_MM_SS);
                      String dms_lon = Coordinates.convert(Math.abs(wp.getLongitude()),Coordinates.DD_MM_SS);
//System.out.println("Lat="+dms_lat);
                      latitudeDirectionField.setSelectedIndex((wp.getLatitude() > 0) ?0 : 1);
                      longitudeDirectionField.setSelectedIndex((wp.getLongitude() > 0) ?0 : 1);

                      int dmsSep1 = dms_lat.indexOf(":");
                      int dmsSep2 = dms_lat.indexOf(":",dmsSep1+1);
                      //System.out.println(dms_lat.substring(0,dmsSep1));
                      //System.out.println(dms_lat.substring(dmsSep1+1,dmsSep2));
                      //System.out.println(dms_lat.substring(dmsSep2+1,dms_lat.length()));

                      latitudeIntField.setText(dms_lat.substring(0,dmsSep1));
                      latitudeIntMMField.setText(dms_lat.substring(dmsSep1+1,dmsSep2));
                      latitudeDecField.setText(dms_lat.substring(dmsSep2+1,dms_lat.length()));

                      dmsSep1 = dms_lon.indexOf(":");
                      dmsSep2 = dms_lon.indexOf(":",dmsSep1+1);
                      longitudeIntField.setText(dms_lon.substring(0,dmsSep1));
                      longitudeIntMMField.setText(dms_lon.substring(dmsSep1+1,dmsSep2));
                      longitudeDecField.setText(dms_lon.substring(dmsSep2+1,dms_lon.length()));
                      break;

              case 3: CoordinateConversion conv = new CoordinateConversion();
                      String mgrutm = conv.latLon2MGRUTM(wp.getLatitude(),wp.getLongitude());
                      int zone = Integer.parseInt(mgrutm.substring(0, 2));
                      MGRSGridZoneNumField.setSelectedValue(zone);

                      String latZone = mgrutm.substring(2, 3);
                      for (int i=0;i<gridAlphaChoices.length;i++) {
                          if (latZone.equals(gridAlphaChoices[i])) {
                              MGRSGridZoneAlphaField.setSelectedIndex(i);
                          }
                      }

                      String digraph1 = mgrutm.substring(3, 4);
                      String digraph2 = mgrutm.substring(4, 5);
                      MGRSGridField.setText(digraph1+digraph2);

                      MGRSEastingField.setText(mgrutm.substring(5, 10));
                      MGRSNorthingField.setText(mgrutm.substring(10, 15));
                      break;
              }
              Date wpDate = new Date(wp.getWptDate());
              dateField.setDate(wpDate);
              descriptionField.setText(wp.getDescription());
              shortDescField.setText(wp.getShortDescription());
              longDescField.setText(wp.getLongDescription());
        }
    }

    public MenuItem storeMenuItem = new MenuItem("Save Waypoint", 1,1){
        public void run(){
            save();
             UiApplication.getUiApplication().popScreen();
        }
    };


    public void save() {
            Coordinates coord = new Coordinates(0,0,0);
           switch (Options.getCoordFormat()) {
             case 0: double destLat =  Double.parseDouble(latitudeField.getText());
                     double destLong =  Double.parseDouble(longitudeField.getText());
                     try {
                          coord = new Coordinates(destLat, destLong, 0);
                     } catch (IllegalArgumentException e) {
                        Dialog.alert("Error: " + e.getMessage());
                     }  
                     break;

             case 1: double lat = Double.parseDouble(latitudeDecField.getText());
                     lat /= 60d;
                     lat += Double.parseDouble(latitudeIntField.getText());
                     if (latitudeDirectionField.getSelectedIndex() == 1) {
                        lat *=  -1d;
                     }

                     double lon = Double.parseDouble(longitudeDecField.getText());
                     lon /= 60d;
                     lon += Double.parseDouble(longitudeIntField.getText());
                     if (longitudeDirectionField.getSelectedIndex() == 1) {
                        lon *=  -1d;
                     }
                     
                     try {
                        coord = new Coordinates(lat, lon, 0);
                     } catch (IllegalArgumentException e) {
                        Dialog.alert("Error: " + e.getMessage());
                     }  
                     break;

             case 2: double dms_lat = Double.parseDouble(latitudeDecField.getText()) / 3600d;
                     dms_lat += Double.parseDouble(latitudeIntMMField.getText()) / 60d;
                     dms_lat += Double.parseDouble(latitudeIntField.getText());
                     if (latitudeDirectionField.getSelectedIndex() == 1) {
                        dms_lat *=  -1d;
                     }

                     double dms_lon = Double.parseDouble(longitudeDecField.getText()) / 3600d;
                     dms_lon += Double.parseDouble(longitudeIntMMField.getText()) / 60d;
                     dms_lon += Double.parseDouble(longitudeIntField.getText());
                     if (longitudeDirectionField.getSelectedIndex() == 1) {
                        dms_lon *=  -1d;
                     }
                     
                     try {
                        coord = new Coordinates(dms_lat, dms_lon, 0);
                     } catch (IllegalArgumentException e) {
                        Dialog.alert("Error: " + e.getMessage());
                     }  
                     break;

             case 3: StringBuffer sb = new StringBuffer();
                     int gridZone =  MGRSGridZoneNumField.getSelectedValue();
                     if (gridZone < 10) {
                       sb.append("0" + gridZone);
                     } else {
                       sb.append(""+gridZone);
                     }
                     sb.append((String)MGRSGridZoneAlphaField.getChoice(MGRSGridZoneAlphaField.getSelectedIndex()));
                     sb.append(MGRSGridField.getText());
                     sb.append(MGRSEastingField.getText());
                     sb.append(MGRSNorthingField.getText());
                     CoordinateConversion conv = new CoordinateConversion();
                     double[] c = conv.mgrutm2LatLon(sb.toString());
                     try {
                        coord = new Coordinates(c[0],c[1], 0);
                     } catch (IllegalArgumentException e) {
                        Dialog.alert("Error: " + e.getMessage() + "\n"+c[0]+"\n"+c[1]);
                     }  
                         
                     break;
             }

            
            //Waypoint wp = new Waypoint();
            //wp = new Waypoint(nameField.getText(), coord.getLatitude(), coord.getLongitude(), coord.getAltitude());
            currentWaypoint.setName(nameField.getText());
            currentWaypoint.setLatitude(coord.getLatitude());
            currentWaypoint.setLongitude(coord.getLongitude());
            currentWaypoint.setAltitude(coord.getAltitude());
            currentWaypoint.setDescription(descriptionField.getText());
            currentWaypoint.setWptDate(dateField.getDate());
            
             WaypointsDAO dao = new WaypointsDAO();
             
             if (currentWaypoint.getKeyName() != null) {
                 dao.deleteWaypoint(currentWaypoint);
             }
             dao.storeWaypoint (currentWaypoint);
    }
    
    public MenuItem testMenuItem = new MenuItem("Import GPX/LOC File", 3,3){
        public void run(){ UiApplication.getUiApplication().popScreen();UiApplication.getUiApplication().pushScreen(new FileExplorerScreen()); }
    };

/*    public MenuItem aboutMenuItem = new MenuItem("About", 3,3){
        public void run(){
            Dialog.inform("This application has been designed for non-commercial use. Any queries please contact me via paul.haenel@gmail.com!");
        }
    };

    public MenuItem exitMenuItem = new MenuItem("Exit", 4,4){
        public void run(){ onClose(); }
    };
    
    public boolean onClose(){
        int answ = Dialog.ask(Dialog.D_YES_NO, "Are you sure you want to close BlackStar?");
        if(answ == Dialog.YES) System.exit(1);
        return true;
    }
*/
    protected void makeMenu(Menu menu, int instance){
        menu.add(storeMenuItem);
        menu.add(testMenuItem);
//        menu.add(aboutMenuItem);
//        menu.add(exitMenuItem);
    }
    protected void paintBackground(Graphics g) {
//        setExtent(Graphics.getScreenWidth(), Graphics.getScreenHeight());
//        setVirtualExtent(Graphics.getScreenWidth(), Graphics.getScreenHeight());
        if (Options.getNightMode()) {
            g.setBackgroundColor(Color.BLACK);
            g.setColor(Color.RED);
        } else {
            g.setBackgroundColor(Color.WHITE);
            g.setColor(Color.BLACK);
        }
        g.clear();
        g.fillRect(0,0,Graphics.getScreenWidth(), Graphics.getScreenHeight());
    }
    

}

